//
//  YCSpeedDialView.m
//  Pods
//
//  Created by Sheng long on 16/1/18.
//
//

#import "YCSpeedDialView.h"
#import "CommUtls+NSInteger.h"
#import <Masonry/Masonry.h>
#import <ReactiveCocoa/ReactiveCocoa.h>

typedef void(^ClickItems)(NSInteger index);

@interface YCSpeedDialView ()

@property (nonatomic,copy) ClickItems click;

@end

@implementation YCSpeedDialView

- (void)dealloc{
#ifdef DEBUG
    NSLog(@"dealloc -- %@",self.class);
#endif
}

- (void)fetchClickItems:(void(^)(NSInteger index))clickIndex{
    self.click = clickIndex;
    NSInteger yNum = [CommUtls numOverInt:self.imageNames.count divide:self.lineNum];
    CGFloat xGap = (self.frame.size.width-self.lineNum*self.itemsSize.width)/(self.lineNum+1);
    CGFloat yGap = (self.frame.size.height-yNum*self.itemsSize.height)*1./(yNum+1);
    
    [self.imageNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIView *view = [self fetchMenuView:self.titles[idx]
                                 imageName:obj
                                     index:idx];
        view.frame = CGRectMake(xGap+(idx%self.lineNum)*(self.itemsSize.width+xGap), yGap+(idx/self.lineNum)*(self.itemsSize.height+yGap), self.itemsSize.width, self.itemsSize.height);
    }];
}

- (UIView *)fetchMenuView:(NSString *)title
                imageName:(NSString *)imageName
                    index:(NSInteger)index{
    UIView *view = [UIView new];
    [self addSubview:view];
    
    UIImageView *imageView = [UIImageView new];
    [view addSubview:imageView];
    imageView.image = [UIImage imageNamed:imageName];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.centerX.mas_equalTo(view.mas_centerX);
    }];
    
    UILabel *label = [UILabel new];
    [view addSubview:label];
    label.text = title;
    label.font = self.titlesFont;
    label.textColor = self.titlesColor;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(imageView.mas_bottom).mas_equalTo(5);
        make.centerX.mas_equalTo(view.mas_centerX);
    }];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    @weakify(self);
    [[button rac_signalForControlEvents:UIControlEventTouchDown] subscribeNext:^(id x) {
        @strongify(self);
        if (self.click) {
            self.click(index);
        }
    }];
    
    return view;
}

@end
